package com.three.crm.location;

import android.annotation.SuppressLint;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.three.crm.MyApplication;
import com.three.crm.constant.AppConstant;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.require.AppRequireService;
import com.three.crm.util.AppManager;
import com.three.crm.util.SignUtil;
import com.three.crm.util.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

public class LocationUtils {

    @SuppressLint("StaticFieldLeak")
    private static AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption = null;
    private OnAMapLocationListener onAMapLocationListener;

    public void setOnAMapLocationListener(OnAMapLocationListener monAMapLocationListener) {
        this.onAMapLocationListener = monAMapLocationListener;
    }

    private static class LocationHolder {
        private static final LocationUtils INSTANCE = new LocationUtils();
    }

    public static LocationUtils getInstance() {
        return LocationHolder.INSTANCE;
    }

    public void startLocalService(OnAMapLocationListener onAMapLocationListener) {
        Log.i("TAG","开始定位...");
        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(MyApplication.getContext());
            //设置定位回调监听
            mLocationOption = getDefaultOption();
            mLocationClient.setLocationOption(mLocationOption);

            mLocationClient.startLocation();
            mLocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation aMapLocation) {
                    Log.i("TAG","address=" + aMapLocation.getAddress());
                    Log.i("TAG","lat=" + aMapLocation.getLatitude());
                    Log.i("TAG","lnt=" + aMapLocation.getLongitude());

                    if (null != aMapLocation) {
                        if (aMapLocation.getErrorCode() == 0) {
                            Log.i("TAG","stopLocalService=");
                            stopLocalService();
                        }
                        if (onAMapLocationListener != null) {
                            onAMapLocationListener.getLocation(aMapLocation);
                        }
                    } else {
                        if (onAMapLocationListener != null) {
                            onAMapLocationListener.getLocation(null);
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopLocalService() {
        if (null != mLocationClient) {
            mLocationClient.stopLocation();
        }
    }

    public void destroyLocation() {
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true

        //mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(true);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(false); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }

    public void onUploadLocation(double latitude, double longitude) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("latitude",String.valueOf(latitude));
            jsonObject.put("longitude",String.valueOf(longitude));
            jsonObject.put("timestamp",AppManager.getTimesTamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.uploadLocation(MyApplication.getContext(), AppConstant.FORM_SUBMIT, jsonObject, new CommonResultCallBack(MyApplication.getContext()) {
                @Override
                public void onResult(String result, int requireCode) {
                    if (requireCode == AppConstant.FORM_SUBMIT) {
                        Log.i("TAG","上传当前位置成功！");
                        //ToastUtils.showToast("上传当前位置成功");
                    }
                }

                @Override
                public void onConnectTimeOut(Call call, Exception e, int requireCode) {

                }

                @Override
                public void onFail(String msg, int requireCode) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public interface OnAMapLocationListener{
        void getLocation(AMapLocation aMapLocation);
    }
}
